define([
        'Util',
        'text!tpl/order/editOrder.tpl',
        'select',
        'provincesSelect',
        'date',
        'list',
        'form',
        'upload',
        'dialog',
        'jquery',
        'checkboxes',
        'validator',
        'loading',
        'cookie',
        '../common/getPath',
        'comboSelect',
        'js/order/fileList',
        'radios'
    ],
    function (Util, tpl, Select, provincesSelect, MyDate,List ,Form, Upload, Dialog, $, Checkboxes, Validator, Loading, $cookie, AjaxPath, ComboSelect, fileList, Radios) {
        require(['style!css/style.css']);
        //系统变量-定义该模块的根节点
        var $el = null;
        var _indexModule = null,
        	reqAttachmentIdList = [],
        	htDemandUnitSelect = null,   //需求单位
        	htDemandUnitSelectValue = null, //需求单位val
        	htPrioritySelect = null, //优先级
        	htPrioritySelectValue = null, //优先级Val
        	/*htOrderTypeSelect = null,  //下单类型
        	htOrderTypeSelectValue = null,*/
        	htContractSelect = null,//合同情况
        	htContractSelectValue = null,
        	htEquipmentTypeSelect = null, //设备类型
        	htEquipmentTypeSelectValue = null,
        	htEquipmentNotaxPrice = null,// 不含税单价
        	htEquipmentPrice = null,   // 含税单价
        	OrderValidation = null, //验证
        	OrderValidationOne = null, //验证
        	OrderValidationTwo = null, //验证
        	attachmentsIdsArr = [],
        	fileStatus = false,
        	delFlag = false,
        	uploadDialog = null,
         	editOrderData = null;
        //系统变量-构造函数
        var initialize = function(indexModule, options, tabItem) {
            $el = $(tpl);
            _indexModule = indexModule;
            $(tabItem).on("tabActive", function() {
                tabItem.show(true); //刷新表单
            });
            editOrderData = options;
            tabOrder = tabItem;
            this.content = $el;
            //下拉框
            htSelect();
            //查询工单
            viewOrderInfo();
            eventInit();
            addOrderValidation();//验证
            //addOrderValidation();
        };
        //业务代码-事件初始化
        var eventInit = function() {
            $el.on('click','.submitBtn',editOrderBtn);//提交
            $el.on('click','.saveBtn', editOrderBtn);//保存
            $el.on('click','.btnBack',btnBack);
          /*  $el.on('click', '.templateOne', templateOne);
            $el.on('click', '.templateTwo', templateTwo);
            $el.on('click', '.templateThree', templateThree);*/
            $el.on('blur','.htnoTaxPrice , .httaxPrice , .htequipmentNum',htNoTaxTotalFn);//计算总价
            $el.on('blur','.httaxPrice , .htnoTaxPrice',fill0);//单价补0
        };
        var fill0 = function(){
        	var val = $(this).val()-0;
        	var val2 = val.toFixed(2);
        	$(this).val(val2);
        }
        var viewOrderInfo = function(){
        	Util.ajax.getJson(AjaxPath.management + "/order/findOrder?id="+editOrderData.id, function(result, isok){
        	//Util.ajax.getJson(AjaxPath.management + "/order/findOrder?id=5", function(result, isok){
        		
        		if (result.returnCode === "0000") {
        			editOrderData = result.bean;
        			//赋值	
        		 	for(let keys in result.bean){
						if($('.htEditOrderFrom',$el).find('.ht'+keys)){
							$('.htEditOrderFrom',$el).find('.ht'+keys).val($.trim(result.bean[keys]));
						}
		        	}
        		 	if(result.bean.demandEmployer === 1){//分公司自采0客户采购1
        		 		$('.ifShow').hide();
        		 		if(!editOrderData.contractStatus){//已签署 未签署
	                		$('.templateTwo',$el).show();                		
	                		$('.templateThree',$el).show();
	                		$('.templateFour',$el).hide();
	                		$('.templateFive').hide();
	                	}else if(editOrderData.contractStatus){
	                		$('.templateTwo',$el).show();
	                		$('.templateThree',$el).hide();
	                		$('.templateFour',$el).hide();
	                		$('.templateFive').show();
	                	}
        		 		//判断是否显示合同编号合同名称
        		 		if(result.bean.contractStatus !== 0){
        		 			$('.htContractNum',$el).hide();
        		 			$('.htContractName',$el).hide();
        		 		}
        		 	}else{//分公司自采0
        		 		$('.ifShow').show();
        		 		$('.templateTwo',$el).hide();                		
                		$('.templateThree',$el).hide();
                		$('.templateFour',$el).show();
                		$('.templateFive').hide();
        		 		//含税单价，不含税单价，含税总价 ，不含税总价  隐藏
        		 		for(var i=0;i<$('.htPrice',$el).length;i++){
        		 			$('.htPrice',$el).eq(i).hide();
        		 			//合同编号， 合同情况，下单类型，合同名称
        		 			$('.htHide',$el).eq(i).hide();
        		 			$('.htPrice',$el).eq(i).find('input').val('');
        		 			$('.htHide',$el).eq(i).find('input').val('');
        		 		}
        		 	}
        		 	htOrderSelectUrl(result.bean);//需求单位 、 设备类型  、最晚发货日期  、 最早发货日期 、 提出日期 、 优先级
        		 	htTimeData(result.bean);// 提出日期、最早发货日期、最晚发货日期
        		 	new provincesSelect({
		                    elProvices:$("#province", $el),
		                    elCity:$("#city", $el),
		                    elTown:$("#town", $el)
		               },
		               result.bean.addrProvince,
		               result.bean.addrCity
		            );
		            $("#province",$el).find("option[value='"+result.bean.addrProvince+"']").attr("selected",true);
		            $("#city",$el).find("option[value='"+result.bean.addrCity+"']").attr("selected",true);
		            $("#town",$el).find("option[value='"+result.bean.addrCounty+"']").attr("selected",true);
		            //附件
		            fileUp();
		            //附件回显
        			fileTable();
                } else {
                    new Dialog({
                        mode: 'confirm', // 对话框模式，默认normal标准|confirm浮动层|confirm确认对话框
                        title: '提示',
                        width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                        height: 120, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                        cancelDisplay: false, //是否显示取消按钮（强制执行，可在confirm模式下生效），可选项。 默认true(显示)
                        modal: true,
                        content: '<div style="text-align:center;margin-top:50px">' + result.returnMessage + '</div>'// 对话框内容，可以是字符串、html片段、或dom对象,默认为loading状态（点组成的圈）
                    });
                }
        		
        	})
        };
        //不含税单总价
        var htNoTaxTotalFn = function(){
        	var NoTotal = 0,Total = 0;
        	if(htDemandUnitSelectValue === 0){
        		NoTotal = htEquipmentNotaxPrice * $('.htequipmentNum',$el).val();
        		Total = htEquipmentPrice * $('.htequipmentNum',$el).val();
        		$('.htnoTaxTotal',$el).val(NoTotal.toFixed(2));
        		$('.httaxTotal',$el).val(Total.toFixed(2));
        	}else if(htDemandUnitSelectValue === 1){
        		NoTotal = $('.htnoTaxPrice',$el).val() * $('.htequipmentNum',$el).val();
        		Total = $('.httaxPrice',$el).val() * $('.htequipmentNum',$el).val();
        		$('.htnoTaxTotal',$el).val(NoTotal.toFixed(2));
        		$('.httaxTotal',$el).val(Total.toFixed(2));
        	}
        }
        //时间戳转换
        var htTimeConversion = function getMyDate(str){  
            var oDate = new Date(str),  
            oYear = oDate.getFullYear(),  
            oMonth = oDate.getMonth()+1,  
            oDay = oDate.getDate(),  
            //oHour = oDate.getHours(),  
            //oMin = oDate.getMinutes(),  
            //oSen = oDate.getSeconds(),  
            oTime = oYear +'-'+oMonth+'-'+oDay;
            //oTime = oYear +'-'+oMonth+'-'+oDay +' '+oHour+':'+oMin+':'+oSen;//最后拼接时间  
            return oTime;  
        }; 
        
      /*  /!*模板下载*!/
        var templateOne=function () {
            window.location.href="http://192.168.26.27:8001/file-service/dev-yanfayun/bbe4357a-afc9-4227-a255-415d8ccd8754/%E6%94%B6%E8%B4%A7%E5%9C%B0%E5%9D%80%E5%A1%AB%E5%86%99%E6%A8%A1%E6%9D%BF.xlsx"; //地址模板
        };
        var templateThree=function () { //采购模板
            window.location.href="http://192.168.26.27:8001/file-service/dev-yanfayun/91f5c4d3-97d5-4bdb-8c21-73745d3b142d/%E9%87%87%E8%B4%AD%E8%AE%A2%E5%8D%95%E6%A8%A1%E6%9D%BF.docx"
        };
        var templateTwo=function () {//合同关键页
            window.location.href="http://192.168.26.27:8001/file-service/dev-yanfayun/5df4f8ec-59bd-48ff-8909-f064b72088a8/%E5%90%88%E5%90%8C%E5%85%B3%E9%94%AE%E9%A1%B5.pdf";
        };*/

		//面包屑
        var btnBack = function() {
            tabOrder.switchTab(editOrderData.menuId);
            tabOrder.destroy("editOrderTab");
        };
        /*需求单位、优先级   、下单类型  下拉框*/
		var htSelect = function(){
			//需求单位
			htDemandUnitSelect = new Select({
                el:$(".htDemandUnitSelect",$el),       //要绑定的容器
                ajax:{    //所有jquery.ajax的配置项均可配置，这些配置将替换底层组件的配置，<span class="s">慎用</span>
                    method:'GET'
                },
                label:'<i style="color:red;padding:2px;">*&nbsp;</i>需求单位:', //下拉框单元左侧label文本，可不配置
                selectText:false,       //是否显示  ‘选择|清除’  模式
                name:'htDemandUnitSelect',    //下拉框单元右侧下拉框名称
                disabled:false,     //组件是否被禁用
                topOption:"", //设置最顶部option的text属性
                value:'dictValue',//初始选中项设置 默认是按value，如果你想按id设置 也可以 value:[&quot;id&quot;,1],这样设置
                textField:"dictName",   //设置下拉框内容，填写数据中对应的字段名
                valueField:"dictValue",//设置下拉框value，填写数据中对应的字段名
                datas: [],         //数据源
                loadAtClick:false,// true--第一次点击时渲染|false或不配置--初始化时渲染
                dataReady:function(){}
            });
            /*优先级*/
            htPrioritySelect = new Select({
                el:$(".htPrioritySelect",$el),       //要绑定的容器
                ajax:{    //所有jquery.ajax的配置项均可配置，这些配置将替换底层组件的配置，<span class="s">慎用</span>
                    method:'GET'
                },
                label:'<i style="color:red;padding:2px;">*&nbsp;</i>优先级:', //下拉框单元左侧label文本，可不配置
                selectText:false,       //是否显示  ‘选择|清除’  模式
                name:'htPrioritySelect',    //下拉框单元右侧下拉框名称
                disabled:false,     //组件是否被禁用
                topOption:"", //设置最顶部option的text属性
                value:'dictValue',//初始选中项设置 默认是按value，如果你想按id设置 也可以 value:[&quot;id&quot;,1],这样设置
                textField:"dictName",   //设置下拉框内容，填写数据中对应的字段名
                valueField:"dictName",//设置下拉框value，填写数据中对应的字段名
                datas: [],         //数据源
                loadAtClick:false,// true--第一次点击时渲染|false或不配置--初始化时渲染
                dataReady:function(){}
            });
           /* //下单类型
            htOrderTypeSelect = new Select({
                el:$(".htOrderTypeSelect", $el),       //要绑定的容器
                ajax:{    //所有jquery.ajax的配置项均可配置，这些配置将替换底层组件的配置，<span class="s">慎用</span>
                    method:'GET'
                },
                label:'<i style="color:red;padding:2px;">*&nbsp;</i>下单类型:', //下拉框单元左侧label文本，可不配置
                selectText:false,       //是否显示  ‘选择|清除’  模式
                name:'orderType',    //下拉框单元右侧下拉框名称
                disabled:false,     //组件是否被禁用
                topOption:"", //设置最顶部option的text属性
                value:'dictValue',//初始选中项设置 默认是按value，如果你想按id设置 也可以 value:[&quot;id&quot;,1],这样设置
                textField:"dictName",   //设置下拉框内容，填写数据中对应的字段名
                valueField:"dictValue",//设置下拉框value，填写数据中对应的字段名
                datas: [],         //数据源
                loadAtClick:false,// true--第一次点击时渲染|false或不配置--初始化时渲染
                dataReady:function(){
                    //console.log("下单类型");
                }
            });*/
            //合同情况
            htContractSelect = new Select({
                el:$(".htContractSelect", $el),       //要绑定的容器
                ajax:{    //所有jquery.ajax的配置项均可配置，这些配置将替换底层组件的配置，<span class="s">慎用</span>
                    method:'GET'
                },
                label:'<i style="color:red;padding:2px;">*&nbsp;</i>合同情况:', //下拉框单元左侧label文本，可不配置
                selectText:false,       //是否显示  ‘选择|清除’  模式
                name:'contract',    //下拉框单元右侧下拉框名称
                disabled:false,     //组件是否被禁用
                topOption:"", //设置最顶部option的text属性
                value:'dictValue',//初始选中项设置 默认是按value，如果你想按id设置 也可以 value:[&quot;id&quot;,1],这样设置
                textField:"dictName",   //设置下拉框内容，填写数据中对应的字段名
                valueField:"dictValue",//设置下拉框value，填写数据中对应的字段名
                datas: [],         //数据源
                loadAtClick:false,// true--第一次点击时渲染|false或不配置--初始化时渲染
                dataReady:function(){
                    //console.log("合同情况");
                }
            });
            //设备类型
            htEquipmentTypeSelect = new Select({
                el:$(".htEquipmentTypeSelect", $el),       //要绑定的容器
                ajax:{    //所有jquery.ajax的配置项均可配置，这些配置将替换底层组件的配置，<span class="s">慎用</span>
                    method:'GET'
                },
                label:'<i style="color:red;padding:2px;">*&nbsp;</i>设备类型:', //下拉框单元左侧label文本，可不配置
                selectText:false,       //是否显示  ‘选择|清除’  模式
                name:'equipmentName',    //下拉框单元右侧下拉框名称
                disabled:false,     //组件是否被禁用
                topOption:"请选择", //设置最顶部option的text属性
                value:'',//初始选中项设置 默认是按value，如果你想按id设置 也可以 value:[&quot;id&quot;,1],这样设置
                textField:"equipmentName",   //设置下拉框内容，填写数据中对应的字段名
                valueField:"id",//设置下拉框value，填写数据中对应的字段名
                datas: [],         //数据源
                loadAtClick:false,// true--第一次点击时渲染|false或不配置--初始化时渲染
                dataReady:function(){}
            });
		}
        /*需求单位、优先级   、下单类型  接口*/
        var htOrderSelectUrl = function (oData) {
        	//需求单位
            Util.ajax.getJson(AjaxPath.management+"/dict/dropDown?businessModual=orderList&businessType=demandEmployer", function(result, isok) {
                htDemandUnitSelect.reload(result.beans);
            	htDemandUnitSelect.setValue(0);
            	htDemandUnitSelect.setValue(oData.demandEmployer);
            	htDemandUnitSelectValue = oData.demandEmployer;
            	htDemandUnitSelect.on('change',function(e,valueObj){
            		htDemandUnitSelectValue = valueObj.dictValue;
	        		//0分公司  1总公司
	        		if(valueObj.dictValue === 0){
	        			$('.ifShow').show();
        		 		$('.templateTwo',$el).hide();                		
                		$('.templateThree',$el).hide();
                		$('.templateFour',$el).show();
                		$('.templateFive').hide();
	        			//合同编号， 合同情况，下单类型，合同名称
	        			for(var i=0;i<$('.htPrice',$el).length;i++){
        		 			$('.htPrice',$el).eq(i).hide();
        		 			$('.htHide',$el).eq(i).hide();
        		 			$('.htPrice',$el).eq(i).find('input').val('');
        		 			$('.htHide',$el).eq(i).find('input').val('');
        		 		};
	        		}else if(valueObj.dictValue === 1){
	        			$('.ifShow').hide();
	        			for(var i=0;i<$('.htPrice',$el).length;i++){
        		 			$('.htPrice',$el).eq(i).show();
        		 			$('.htHide',$el).eq(i).show();
        		 		}
	        			
	        			
	        			if(htContractSelectValue === 0){
        		 			$('.templateTwo',$el).show();                		
	                		$('.templateThree',$el).show();
	                		$('.templateFour',$el).hide();
	                		$('.templateFive').hide();
        		 		}else{
        		 			$('.templateTwo',$el).show();
	                		$('.templateThree',$el).hide();
	                		$('.templateFour',$el).hide();
	                		$('.templateFive').show();
        		 		}
	        			//判断 下单类型 合同情况
        		 		if(htContractSelectValue === 0){
        		 			$('.htContractNum',$el).show();
        		 			$('.htContractName',$el).show();
        		 		}else{
        		 			$('.htContractNum',$el).hide();
        		 			$('.htContractName',$el).hide();
        		 		}
	        		}
	                
	            });
            });
        	//优先级
            Util.ajax.getJson(AjaxPath.management+"/dict/dropDown?businessModual=orderList&businessType=priority", function(result, isok) {
                htPrioritySelect.reload(result.beans);
                htPrioritySelect.setValue(0);
                htPrioritySelect.setValue(oData.priority);
                htPrioritySelectValue= oData.priority;
                htPrioritySelect.on('change',function(e,valueObj){
                	htPrioritySelectValue = valueObj.dictValue;
	            });
            });
            /*//下单类型
            Util.ajax.getJson(AjaxPath.management+"/dict/dropDown?businessModual=orderList&businessType=orderType", function(result, isok) {
               	htOrderTypeSelect.reload(result.beans);
                htOrderTypeSelect.setValue(0);
                htOrderTypeSelect.setValue(oData.orderType);
                htOrderTypeSelectValue = htOrderTypeSelect.getSelected('dictValue');
                htOrderTypeSelect.on('change',function(e,valueObj){
                	htOrderTypeSelectValue= valueObj.dictValue;
                	//判断是否显示  合同编号 合同名称
                	if(htOrderTypeSelectValue === 0 && htContractSelectValue === 0){
                		$('.htContractNum',$el).show();
        		 		$('.htContractName',$el).show();
                	}else{
                		$('.htContractNum',$el).val('').hide();
        		 		$('.htContractName',$el).val('').hide();
                	}
	            });
            });*/
            //合同情况
            Util.ajax.getJson(AjaxPath.management+"/dict/dropDown?businessModual=orderList&businessType=contractStatus", function(result, isok) {
                htContractSelect.reload(result.beans);
                htContractSelect.setValue(1);
                htContractSelect.setValue(oData.contractStatus);
                htContractSelectValue= htContractSelect.getSelected('dictValue');
                htContractSelect.on('change',function(e,valueObj){
                	htContractSelectValue = valueObj.dictValue;
                	if(!htContractSelectValue){//已签署
                		$('.templateTwo',$el).show();                		
                		$('.templateThree',$el).show();
                		$('.templateFour',$el).hide();
                		$('.templateFive').hide();
                		$('.htContractNum',$el).show();
        		 		$('.htContractName',$el).show();
                	}else if(htContractSelectValue){
                		$('.templateTwo',$el).show();
                		$('.templateThree',$el).hide();
                		$('.templateFour',$el).hide();
                		$('.templateFive').show();
                		$('.htContractNum',$el).hide();
        		 		$('.htContractName',$el).hide();
                	}
	            });
            });
            //设备类型
            Util.ajax.getJson(AjaxPath.management+"/order/equipmentType", function(result, isok) {
                htEquipmentTypeSelect.reload(result.beans);
                htEquipmentTypeSelect.setValue(0);
                htEquipmentTypeSelect.setValue(oData.equipmentType);
                htEquipmentTypeSelectValue = htEquipmentTypeSelect.getSelected('id');
                var num = oData.equipmentType -1;
                htEquipmentNotaxPrice = result.beans[num].equipmentNotaxPrice;
                htEquipmentPrice = result.beans[num].equipmentPrice;
                htEquipmentTypeSelect.on('change',function(e,valueObj){
                	htEquipmentTypeSelectValue = valueObj.id;
                	htEquipmentNotaxPrice = valueObj.equipmentNotaxPrice;
                	htEquipmentPrice = valueObj.equipmentPrice;
	            });
            });
        };    
		var htTimeData = function(oData){
			//提出日期
            proposeDate = new MyDate({
                el: $(".htProposeDate", $el),
                inputClassName: 'htProposeDateIpt',
                label: '<i style="color:red;padding:2px;">*&nbsp;</i>提出日期:',
                name: 'htProposeDateIpt',    //开始日期文本框name
                isReadOnly: true,  //项可设置日期输入框是否只读
                range: false,
                type: "date",
                isDisabled: false,//是否禁用组件
                defaultValue:htTimeConversion(oData.orderTime),
                btns: ['now', 'confirm'],
                done: function(dates,value,planStartDate){
                	$('.htProposeDateIpt',$el).val(dates);
                	zzfhDateDate.options.min=dates;
                }
            });
            proposeDate.options.max=htTimeConversion(oData.deliveryFirstTime);
            //最早发货日期
            zzfhDateDate = new MyDate({
                el: $(".htDeliveryFirstTime", $el),
                inputClassName: 'htDeliveryFirstTimeIpt',
                label: '<i style="color:red;padding:2px;">*&nbsp;</i>最早发货日期:',
                name: 'htDeliveryFirstTimeIpt',    //开始日期文本框name
                isReadOnly: true,  //项可设置日期输入框是否只读
                range: false,
                type: "date",
                isDisabled: false,//是否禁用组件
                defaultValue:htTimeConversion(oData.deliveryFirstTime),
                btns: ['now', 'confirm'],
                done: function(dates,value,planStartDate){
                	$('.htDeliveryFirstTimeIpt',$el).val(dates);
                	zwfhDateDate.options.min = dates; //最晚发货日期最小日期
                	proposeDate.options.max = dates;
                	//doubleDates.options.double.start.max = datas
                }

            });
            zzfhDateDate.options.min=nowTime(0,'yyyy-MM-dd');
            zzfhDateDate.options.max = htTimeConversion(oData.deliveryLastTime);
            //最晚发货日期
            zwfhDateDate = new MyDate({
                el: $(".htDeliveryLastTime", $el),
                inputClassName: 'htDeliveryLastTimeIpt',
                label: '<i style="color:red;padding:2px;">*&nbsp;</i>最晚发货日期:',
                name: 'htDeliveryLastTimeIpt',    //开始日期文本框name
                isReadOnly: true,  //项可设置日期输入框是否只读
                range: false,
                type: "date",
                min:htTimeConversion(oData.deliveryFirstTime),
                isDisabled: false,//是否禁用组件
                defaultValue:htTimeConversion(oData.deliveryLastTime),
                btns: ['now', 'confirm'],
                done: function(dates,value,planStartDate){
                   zzfhDateDate.options.max = dates; //最早发货日期最大
                   $('.htDeliveryLastTimeIpt',$el).val(dates);
    			}
            });
		}
        /*表单验证*/
        var addOrderValidation = function() {
            OrderValidation = new Validator({
                el: $(".addOrderForm", $el),
                submitBtn: $(".submitBtn,.saveBtn",$el), //触发验证的按钮，可不配置
                dialog: true, //是否弹出验证结果对话框
                pattern: { intege1:"^[1-9]\\d*$",tel:"^[0-9\\-()（）]{7,18}$"},
                rules: {
                    orderName: "required",
                    startTime: "required",
                    endTime: "required",
                    deviceNumber: "required|intege11",
                    province: "required",
                    city: "required",
                    town: "required",
                    detailedAddress: "required",
                    htDemandUnitSelect: "required",
                    contact: "required",
                    contactPhone: "required|tel",
                    equipmentName: "required"
                },
                messages: {
                    orderName: {
                        required: "工单标题不能为空！" 
                    },
                    startTime: {
                        required: "最早发货时间不能为空"
                    },
                    endTime: {
                        required: "最晚发货时间不能为空"
                    },
                    deviceNumber: {
                        required: "设备数量不能为空",
                        intege11: "请输入正整数"
                    },
                    province: {
                        required: "请选择所在省份"
                    },
                    city: {
                        required: "请选择所在市区"
                    },
                    town: {
                        required: "请选择所在县城"
                    },
                    detailedAddress: {
                        required: "请输入详细收货地址"
                    },
                    htDemandUnitSelect: {
                        required: "需求单位不能为空"
                    },
                    contact: {
                        required: "请输入联系人"
                    },
                    contactPhone: {
                        required: "请输入联系电话",
                        tel:"请输入正确的联系电话"
                    },
                    equipmentName: {
                        required: "请选择设备类型"

                    }
                }
            });
            OrderValidation.addMethod("intege11", function(str) {
                return new RegExp("^[1-9]\\d*$").test(str);

            });
            OrderValidationOne = new Validator({
                el: $(".addOrderForm", $el),
                submitBtn: $(".submitBtn,.saveBtn",$el), //触发验证的按钮，可不配置
                dialog: true, //是否弹出验证结果对话框
                //pattern: { intege1:"^[1-9]\\d*|0$"},
                rules: {
                    noTaxPrice: "required|taxPrice",
                    noTaxTotal: "required|taxPrice",
                    TaxPrice: "required|taxPrice",
                    taxTotal: "required|taxPrice",
                    orderType: "required",
                    contract: "required"

                },
                messages: {
                    noTaxPrice: {
                        required: "不含税单价不能为空！",
                        taxPrice: "请输入最多两位小数点的正数"
                    },
                    noTaxTotal: {
                        required: "不含税总价不能为空",
                        taxPrice: "请输入最多两位小数点的正数"
                    },
                    TaxPrice: {
                        required: "含税单价不能为空",
                        taxPrice: "请输入最多两位小数点的正数"
                    },
                    taxTotal: {
                        required: "含税总价不能为空",
                        taxPrice: "请输入最多两位小数点的正数"
                    },
                    contract: {
                        required: "合同类型不能为空"
                    }
                }
                /*
                  orderType: {
                        required: "下单类型不能为空"
                    },*/
            });
            OrderValidationOne.addMethod("taxPrice", function(str) {
                return new RegExp("^(([0-9]+[\.]?[0-9]{1,2})|[1-9])$").test(str) ;

            });

            OrderValidationTwo = new Validator({
                el: $(".addOrderForm", $el),
                submitBtn: $(".submitBtn,.saveBtn",$el), //触发验证的按钮，可不配置
                dialog: true, //是否弹出验证结果对话框
                pattern: { intege1:"^[0-9a-zA-Z]+$"},
                rules: {
                    contractCode: "required",
                    contractName: "required"
                },
                messages: {
                    contractCode: {
                        required: "请输入合同编号"
                        //htbh: "请输入正确的合同编号"
                    },
                    contractName: {
                        required: "请输入合同名称"
                    }
                }
            });
            OrderValidationTwo.addMethod("htbh", function(str) {
                return new RegExp("^[0-9a-zA-Z]+$").test(str) ;

            });
        };
       //附件
        var fileUp = function () {
        	fileStatus = true;
            require(['js/common/dateFormat']);
             uploadConfig = {
                el: $("#upload", $el), //组件绑定的容器
                className: 'upload', //组件外围的className
                url: AjaxPath.management+'/attachment/addFile', //组件上传的后台接口
                // url: fileAjaxPath, //组件上传的后台接口
                // deleteUrl: 'data/upload.json?name=[name]', //组件上传的后台接口
                paramName:'file'
            };
             filesUpload = new Upload(uploadConfig);

            filesUpload.on('submit',function(e,data){
            	fileStatus = false;
                //formData的数据会和二进制数据一起提交到服务端
                data.formData = { creator:$cookie.get("userId"), businessType:'require', type:1 };
                // data.formData = { creator:1, businessType:'require', type:1 };
            });

            filesUpload.on('done',function(e,data){
            	if(data.files[0].size === 0){
            		var name=data.files[0].name;
					var ael=$('#upload tbody.files').find('[title]')
					$.each(ael, function(i, obj) {
						// console.log(obj,obj.text);
						if(obj.text==name){
							$(obj).parent().parent().parent().remove();
						}
					});
            		//$('#upload .files>tr:last-child',$el).remove();
            		new Dialog({
                        mode: 'tips',
                        delayRmove:2, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
                        tipsType:'success', //tips类型；可选 success | error，默认普通tips。
                        width:320,
                        height:180,
                        content: '<div style="text-align:center;margin-top:90px">不能上传0KB文件</div>'
                    });
            	}else{
	                attachmentsIdsArr.push(data.result.files[0].attId);
            	}
            	fileStatus = true;

            });
            filesUpload.on('remove',function(e,data){
                if(data.attId){
                    delFlag=true;
                    data=data.attId;
                }
                uploadDelete(e,data)
                //e新增自定义remove方法，可根据服务端文件处理结果删除文件列表中的当前行
            });

            filesUpload.on('download',function(e,data){
            	window.location.href= "http://"+window.location.host+AjaxPath.management+'/attachment/downLoadFile/'+data.attId
                /*if(data.attId){
                    delFlag=true;
                    uploadDown(e,data);
                }*/

            });
             filesUpload.on('fail',function(e,data){
             	if(data.files[0].size > 31457280){
             		var ael=$('#upload tbody.files').find('tr');
					$.each(ael, function(i, obj) {
						if($(obj).hasClass('sn-upload-fail')){
							$(obj).remove();
						}
					})
	        		new Dialog({
	                    mode: 'tips',
	                    delayRmove:2, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
	                    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
	                    width:320,
	                    height:180,
	                    content: '<div style="text-align:center;margin-top:90px">上传文件不能大于30M！</div>'
	                });
             	}else{
             		var ael=$('#upload tbody.files').find('tr');
					$.each(ael, function(i, obj) {
						if($(obj).hasClass('sn-upload-fail')){
							console.log($(obj));
							$(obj).remove();
						}
					})
             		new Dialog({
	                    mode: 'tips',
	                    delayRmove:2, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
	                    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
	                    width:320,
	                    height:180,
	                    content: '<div style="text-align:center;margin-top:90px">文件上传失败！</div>'
	                });
             	}
		       	
		        fileStatus = true;
		    })
            
        };
        function uploadDelete(e,data){
        	if(uploadDialog !== null){
        		uploadDialog.remove();
        	}
            //e新增自定义remove方法，可根据服务端文件处理结果删除文件列表中的当前行
            if(delFlag){
                 uploadDialog = new Dialog({
                    title: '提示', //弹窗标题，
                    content: '<div style="text-align:center;margin-top:50px">确定要删除该附件吗？</div>', //弹窗内容，可以是字符串、html代码段,tpl对象。默认为loading状态（由点组成的圈。大段代码建议使用 tpl。
                    okValue: '确定', //确定按钮的文本 默认是 ‘ok’
                    ok: function() {
                        //uploadDialog.remove();
                        
                        Util.ajax.getJson(AjaxPath.management+'/attachment/delete/'+data, {}, function(result, isok){
                            uploadDialog.remove();
                            if(result.returnCode==='0000'){
                            	var arrIds = [];
					        	for(var i=0;i<attachmentsIdsArr.length;i++){
					        		if(attachmentsIdsArr[i] != data){
					        			arrIds.push(attachmentsIdsArr[i])
					        		}
					        	}
					        	attachmentsIdsArr = arrIds;
                               reqAttachmentIdList = $.grep(reqAttachmentIdList,function(i,n){
                                    return i!== data-0;
                                },false);
                               	e.remove();
                                new Dialog({
                                    mode: 'tips',
                                    delayRmove:3, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
                                    tipsType:'tips', //tips类型；可选 success | error，默认普通tips。
                                    maxWidth:'226px', //设置tips对话框的最大宽度,默认为226px。仅在tips对话框下生效，该项存在时，width属性将失效。
                                    content: '删除附件成功！'
                                });
                            }else{
                                new Dialog({
                                    mode: 'tips',
                                    delayRmove:3, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
                                    tipsType:'tips', //tips类型；可选 success | error，默认普通tips。
                                    maxWidth:'226px', //设置tips对话框的最大宽度,默认为226px。仅在tips对话框下生效，该项存在时，width属性将失效。
                                    content: '删除附件失败！'
                                });
                            }

                        });
                        $(".ui-popup-backdrop, .ui-popup,.ui-popup-modal,.ui-popup-show,.ui-popup-focus").remove();
                        return false;
                    },
                    cancel: function() {
                    	uploadDialog.remove();
                    	$(".ui-popup-backdrop, .ui-popup,.ui-popup-modal,.ui-popup-show,.ui-popup-focus").remove();
                    	return false;
                    },
                    cancelValue: '取消', //取消按钮的文本 默认是 ‘关闭’
                    width: 300,
                    height: 120,
                    modal:true
                });
                //uploadDialog.remove();
            }else{
            	if(delFlag){
            		e.remove();
            	}
            }
        }
        function uploadDown(e,data){
        	//console.log(data)
            //e新增自定义remove方法，可根据服务端文件处理结果删除文件列表中的当前行
            if(delFlag){
                window.location.href=data.filePath;
            }else{

            }
        }
        var fileTable = function(){
        	// AjaxPath.management + '/attachment/findAttachment?id='+optionsData.id
            Util.ajax.getJson(AjaxPath.management +'/attachment/findAttachment?id='+ editOrderData.id, {}, function(result, isok){
                var arr = [];
                for(var q=0;q<result.beans.length;q++){
                	arr.push(result.beans[q].id);
                }
                attachmentsIdsArr = arr;
                $('.files').prepend(fileList(result.beans,reqAttachmentIdList));
                $('#upload .uploadDelete').click(function(){
                    delFlag=true;
                    var delNode=$(this).parent().parent().parent('.template-upload');
                    uploadDelete(delNode,$(this).attr('data'))
                });
            })
        };
        
        /*保存 或提交*/
        var editOrderBtn=function(){
        	var _this = this;
        	if(!fileStatus){
        		new Dialog({
				    mode: 'tips',
				    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
				    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
				    width:320,
				    height:180,
				    content: '<div style="text-align:center;margin-top:90px">附件上传中</div>'
				});
				return false;
        	}
        	//验证
        	var attachmentsIds = '';
        	if(attachmentsIdsArr.length!==0){
        		for(var i=0;i<attachmentsIdsArr.length;i++){
	                attachmentsIds+=attachmentsIdsArr[i]+",";
	            }
        	}
        	if(!OrderValidation.form()) {
            	return false;
            }
        	if(htDemandUnitSelectValue === 1){//客户
            	if(!OrderValidationOne.form()) {
	            	return false;
	            }
            	var htnoTaxTotalToFied = $('.htnoTaxTotal',$el).val() - 0;
            	var httaxTotalToFied = $('.httaxTotal',$el).val() - 0;
            	editOrderData.noTaxPrice = $('.htnoTaxPrice',$el).val();  //不含税单价
	            editOrderData.noTaxTotal = htnoTaxTotalToFied.toFixed(2);  //不含税总价价
	            editOrderData.taxPrice = $('.httaxPrice',$el).val();  //含税单价
	            editOrderData.taxTotal = httaxTotalToFied.toFixed(2);  //含税总价价
            	editOrderData.contractStatus = htContractSelectValue;  //合同情况
            	//判断  0已签署 1 未签署
            	if(htContractSelectValue === 0){
            		if(!OrderValidationTwo.form()) {
		            	return false;
		            }
	            	editOrderData.contractCode = $('.htcontractCode',$el).val();  //合同编号
	            	editOrderData.contractName = $('.htcontractName',$el).val();  //合同名称
            	}else{
            		editOrderData.contractName="";
            		editOrderData.contractCode="";
            	}
            	
            }else if(htDemandUnitSelectValue === 0){//分公司自采
            	if(!OrderValidation.form()) {
	            	return false;
	            }
            	editOrderData.orderType = ''; //下单类型
                editOrderData.contractStatus = '';//合同情况
                editOrderData.noTaxPrice = htEquipmentNotaxPrice; //不含税单价
                editOrderData.noTaxTotal = htEquipmentNotaxPrice * $('.htequipmentNum',$el).val();//不含税总价
                editOrderData.taxPrice = htEquipmentNotaxPrice;//含税单价
                editOrderData.taxTotal = htEquipmentNotaxPrice * $('.htequipmentNum',$el).val();//含税总价
            }
            
        	 
        	//数据  //提出人、所属部门、邮箱地址、手机号  默认不能更改
        	editOrderData.orderName = $('.htorderName',$el).val();//工单标题
            editOrderData.demandEmployer = htDemandUnitSelectValue;   //需求单位
            editOrderData.priority = htPrioritySelectValue;  //优先级
            editOrderData.orderTime = $('.htProposeDateIpt',$el).val();  //提出时间
            editOrderData.deliveryFirstTime = $('.htDeliveryFirstTimeIpt',$el).val();  //最早发货时间htTimeConversion
            editOrderData.deliveryLastTime = $('.htDeliveryLastTimeIpt',$el).val();  //最晚发货时间
            editOrderData.equipmentType = htEquipmentTypeSelectValue;  //设备类型
            editOrderData.equipmentNum = $('.htequipmentNum',$el).val();  //设备数量
            editOrderData.addrProvince = $('.province',$el).val();  //省
            editOrderData.addrCity = $('.city',$el).val();  //市
            editOrderData.addrCounty = $('.town',$el).val();  //县
            editOrderData.address = $('.htaddress',$el).val();  //详细地址
            editOrderData.contact = $('.htcontact',$el).val();  //主要联系人
            editOrderData.contactPhone = $('.htcontactPhone',$el).val();  //联系电话
            editOrderData.attachmentsIds = attachmentsIds;
            Util.ajax.postJson(AjaxPath.management+"/order/update/"+editOrderData.id+"?type="+($(this).hasClass('submitBtn')? 'submit':'save'),JSON.stringify(editOrderData), function(result, isok) {
                if (result.returnCode === "0000") {
                    var addOrderData = Form.serialize($('.addOrderForm', $el));
					new Dialog({
					    mode: 'tips',
					    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
					    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
					    width:320,
					    height:180,
					    content: '<div style="text-align:center;margin-top:90px">' + result.returnMessage + '</div>'
					});
                    setTimeout(function(){
                    	btnBack();
                    },1500);
                } else {
                    new Dialog({
                        mode: 'tips',
                        delayRmove:2, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
                        tipsType:'success', //tips类型；可选 success | error，默认普通tips。
                        width:320,
                        height:180,
                        content: '<div style="text-align:center;margin-top:90px">' + result.returnMessage + '</div>'
                    });
                }



            },"application/json");
        };
        


        return initialize;
    });